package com.bening.smsapp.parser.thread;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.apache.commons.pool.PoolableObjectFactory;

public class ThreadObjectFactory implements PoolableObjectFactory {
   /**
    * Logger for this class
    */
   private static final Log log = LogFactory.getLog(ThreadObjectFactory.class);

   /* (non-Javadoc)
    * @see org.apache.commons.pool.PoolableObjectFactory#makeObject()
    */
   public Object makeObject() {
      return new WorkerThread();
   }

   /* (non-Javadoc)
    * @see org.apache.commons.pool.PoolableObjectFactory#destroyObject(java.lang.Object)
    */
   public void destroyObject(Object obj) {
      if (obj instanceof WorkerThread) {
         WorkerThread rt = (WorkerThread) obj;
         rt.setStopped(true);
      }
   }

   /* (non-Javadoc)
    * @see org.apache.commons.pool.PoolableObjectFactory#validateObject(java.lang.Object)
    */
   public boolean validateObject(Object obj) {
      if (obj instanceof WorkerThread) {
         WorkerThread rt = (WorkerThread) obj;
         if(!rt.isDone()) {  //if the thread is running the previous task, get another one.
            return false;
         }
         if (rt.isRunning()) {
            if (rt.getThreadGroup() == null) {
               return false;
            }
            return true;
         }
      }
      return true;
   }

   /* (non-Javadoc)
    * @see org.apache.commons.pool.PoolableObjectFactory#activateObject(java.lang.Object)
    */
   public void activateObject(Object obj) {
   }

   /* (non-Javadoc)
    * @see org.apache.commons.pool.PoolableObjectFactory#passivateObject(java.lang.Object)
    */
   public void passivateObject(Object obj) {
      if (obj instanceof WorkerThread) {
         WorkerThread wt = (WorkerThread) obj;
         wt = null;
      }
   }

}